import echarts from 'echarts';
import { formatTen } from '@/assets/js/help.js';
import utils from '@/assets/js/utils.js';
export default {
	name: 'Home',
	mixins: [utils],
	data() {
		return {
			operatorName: '',
			authzParkName: '',
			authzParkList: [],
			chartData: [],
			lastMonth: {
				tradeCount: 0,
				traderAmount: 0,
				trendFlow: []
			},
			currentMonth: {
				tradeCount: 0,
				traderAmount: 0,
				trendFlow: []
			},
			allTrendFlow: [],
			noticeList: [],
			isLoadedOneMonth: false,
			isRender: false,
			dialogVisible: false,
			signedPark: null,
			merchantList: []
		};
	},

	computed: {
		allMenu() {
			let allMenu = this.$store.state.menu.allMenu;
			if (allMenu.list && allMenu.list.length > 0) {
				this.isRender = true;
			}
			return allMenu;
		}
	},

	mounted() {
		const self = this;

		this.fetchUnsignedParkList();

		this.$root.eventBus.$on('initPageFn', () => {
			setTimeout(() => {
				this.initPageFn();
			}, 500);
		});
	},
	methods: {
		async noticeLinkTo(type) {
			if (type === 3) {
				await Promise.all([this.fetchUnsignedParkList(), this.fetchPaymentMerchantConfigList()]);
				if (this.signedPark.parkList && this.signedPark.parkList.length && this.merchantList.length) {
					this.dialogVisible = true;
				}
			}
		},

		fetchPaymentMerchantConfigList() {
			return API.fetchGet('/valueAdded/getPaymentMerchantConfigList.do').then(res => {
				this.merchantList = res.data;
			});
		},

		fetchUnsignedParkList() {
			return new Promise(resolve => {
				API.fetchGet('/valueAdded/getUnsignedParkList.do').then(res => {
					this.signedPark = res.data;
					this.signedPark.parkinglotStr = res.data.parkList.map(item => item.name).join('、');
					resolve(true);
				});
			});
		},
		initPageFn() {
			this.allTrendFlow = [];
			this.isLoadedOneMonth = false;
			this.getOperatorName();
			this.getAuthzParks();
			this.pageListMessage();
			this.getLastMonthInfo();
			this.getCurrentMonthInfo();
		},

		// 获取运营商名称
		getOperatorName() {
			let self = this;
			API.fetchGet('/index/getOperatorName.do', {}).then(
				res => {
					if (res && res.data) {
						self.operatorName = res.data;
						return;
					}
					self.operatorName = '';
				},
				err => {
					self.operatorName = '';
				}
			);
		},

		// 获取帐号所有停车场列表
		getAuthzParks() {
			let self = this;
			API.fetchGet('/index/getAuthzParks.do', {}).then(
				res => {
					if (res && res.data) {
						let _list = res.data;
						if (_list && _list.length > 0) {
							if (_list.length === 1) {
								self.authzParkName = _list[0].name;
							} else {
								self.authzParkName = _list.length;
							}
							self.authzParkList = _list;
							return;
						}
					}
					self.authzParkList = [];
					self.authzParkName = 0;
				},
				err => {
					self.authzParkList = [];
					self.authzParkName = 0;
				}
			);
		},

		// 分页获取公告列表
		pageListMessage() {
			let self = this;
			let params = {
				page: 1,
				rp: 5
			};
			API.fetchGet('/index/pageListMessage.do', params).then(
				res => {
					if (res && res.data) {
						let _data = res.data;
						self.noticeList = _data.rows;
						const item = self.noticeList.find(item => item.messageType === 3);
						if (item) {
							self.noticeLinkTo(3);
						}
						return;
					}
					self.noticeList = [];
				},
				err => {}
			);
		},

		// 获取上月数据
		getLastMonthInfo() {
			let self = this;
			API.fetchGet('/index/getLastMonthInfo.do', {}).then(
				res => {
					if (res && res.data) {
						let _data = res.data;
						if (self.count(_data) > 0) {
							self.lastMonth.traderAmount = _data.traderAmount;
							self.lastMonth.tradeCount = _data.tradeCount;
							self.lastMonth.trendFlow = _data.trendFlow;
							self.allTrendFlow = _data.trendFlow.concat(self.allTrendFlow || []);
						}
						if (!self.isLoadedOneMonth) {
							self.isLoadedOneMonth = true;
						} else {
							self.readyToLoadChart();
						}
					}
				},
				err => {
					self.isLoadedOneMonth = true;
				}
			);
		},

		// 获取当月数据和趋势
		getCurrentMonthInfo() {
			let self = this;
			API.fetchGet('/index/getCurrentMonthInfo.do', {}).then(
				res => {
					if (res && res.data) {
						let _data = res.data;
						if (self.count(_data) > 0) {
							self.currentMonth.traderAmount = _data.traderAmount;
							self.currentMonth.tradeCount = _data.tradeCount;
							self.currentMonth.trendFlow = _data.trendFlow;
							self.allTrendFlow = self.allTrendFlow.concat(_data.trendFlow || []);
						}

						if (!self.isLoadedOneMonth) {
							self.isLoadedOneMonth = true;
						} else {
							self.readyToLoadChart();
						}
					}
				},
				err => {
					self.isLoadedOneMonth = true;
				}
			);
		},

		readyToLoadChart() {
			let self = this;
			let resData = [];
			let _dayTime = 24 * 3600 * 1000;
			let _oneDayObj = {
				traderCouponIncomeAmount: 0,
				tempParkingIncomeAmount: 0,
				monthTicketIncomeAmount: 0
			};
			let _allTrendFlow = JSON.parse(JSON.stringify(this.allTrendFlow));
			let _dateTime = '';
			let i = _allTrendFlow.length;
			i--;
			while (i > -1) {
				if (resData.length >= 30) {
					i = -1;
					continue;
				}
				let _info = _allTrendFlow[i];
				let _reportDate = _info.reportDate;
				let _obj = {};
				if (_dateTime) {
					if (_dateTime - _dayTime !== _reportDate) {
						let _date = _dateTime - _dayTime;
						_obj = JSON.parse(JSON.stringify(_oneDayObj));
						_obj.reportDate = _date;
						_obj.formatDate = self.formatDateToMonthDay(_date);
						resData.unshift(_obj);
						_dateTime = _date;
						continue;
					}
				}
				_obj = {
					traderCouponIncomeAmount: _info.traderCouponIncomeAmount,
					tempParkingIncomeAmount: _info.tempParkingIncomeAmount,
					monthTicketIncomeAmount: _info.monthTicketIncomeAmount,
					reportDate: _reportDate,
					formatDate: self.formatDateToMonthDay(_reportDate)
				};
				resData.unshift(_obj);
				_dateTime = _reportDate;
				i--;
			}
			// console.log(resData)
			if (resData.length > 0) {
				this.buildChart(resData);
			}
		},

		buildChart(chartData) {
			let myChart = echarts.init(document.getElementById('chart-box'));

			let xAxisData = []; // 横坐标
			let tpData = []; // 停车费收入
			let mtData = []; // 月票收入
			let tcData = []; // 优惠券收入

			chartData.forEach(item => {
				xAxisData.push(item.formatDate);
				tpData.push(item.tempParkingIncomeAmount);
				mtData.push(item.monthTicketIncomeAmount);
				tcData.push(item.traderCouponIncomeAmount);
			});

			let option = {
				color: ['#5995D8', '#80CCCF', '#8E93E4'],
				tooltip: {
					trigger: 'axis'
				},
				legend: {
					itemWidth: 30,
					itemHeight: 16,
					textStyle: {
						// fontWeight: 600
					},
					right: 40,
					data: ['停车费收入', '月票收入', '优惠券收入']
				},
				grid: {
					left: '3%',
					right: '4%',
					bottom: '3%',
					containLabel: true
				},
				xAxis: {
					type: 'category',
					boundaryGap: false,
					axisLabel: {
						rotate: 45,
						margin: 15
					},
					data: xAxisData
				},
				yAxis: {
					type: 'value'
				},
				series: [
					{
						name: '停车费收入',
						type: 'line',
						itemStyle: {
							borderWidth: 4
						},
						lineStyle: {
							width: 3
						},
						// stack: 'total',
						data: tpData
					},
					{
						name: '月票收入',
						type: 'line',
						itemStyle: {
							borderWidth: 4
						},
						lineStyle: {
							width: 3
						},
						// stack: 'total',
						data: mtData
					},
					{
						name: '优惠券收入',
						type: 'line',
						itemStyle: {
							borderWidth: 4
						},
						lineStyle: {
							width: 3
						},
						// stack: 'total',
						data: tcData
					}
				]
			};

			myChart.setOption(option);
		},

		formatDateToMonthDay(Val, separator, notFormatTen) {
			let result = '';
			separator = separator || '-';
			if (Val) {
				let date = new Date(Val);
				if (notFormatTen) {
					result = date.getMonth() + 1 + separator + date.getDate();
				} else {
					result = formatTen(date.getMonth() + 1) + separator + formatTen(date.getDate());
				}
			}
			return result;
		}
	},

	watch: {
		isRender(Val) {
			if (Val) {
				this.initPageFn();
			}
		}
	},

	filters: {
		/**
		 * 把数字格式化为三位以逗号分隔
		 * @param {*} Val
		 * @param {*} decimalNum  保留小数位
		 */
		formatNumWithComma(Val, decimalNum) {
			if (Val === '') return '';
			if (Number.isNaN(Number(Val))) return Val;

			Val = decimalNum && decimalNum > 0 ? Number(Val).toFixed(decimalNum) : Val;

			let ValArr = (Val + '').split('.');
			let _integer = ValArr[0];
			let _decimal = ValArr[1];

			let _res = parseFloat(_integer).toLocaleString();
			if (_decimal) {
				_res += '.' + _decimal;
			}
			return _res;
		}
	}

	// activated () {
	//   this.initPageFn()
	// },

	// 首页相关api
	// 分页获取公告列表
	// /index/pageListMessage.do

	// 读取公告内容并且置为已读
	// /index/getMessageContent.do

	// 获取运营商名称
	// /index/getOperatorName.do

	// 获取帐号所有停车场列表
	// /index/getAuthzParks.do

	// 获取上月数据
	// /index/getLastMonthInfo.do

	// 获取当月数据和趋势
	// /index/getCurrentMonthInfo.do
};
